﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using System.IO;
using System.Xml.Linq;

namespace TAXILISM.Class
{
    public class TwitPic
    {
        private const string TWITPIC_UPLADO_API_URL = "http://api.twitpic.com/2/upload";
        private const string TWITPIC_UPLOAD_AND_POST_API_URL = "http://api.twitpic.com/1/uploadAndPost";
     
        ///  
        /// Uploads the photo and sends a new Tweet 
        ///  
        /// <param name="binaryImageData">The binary image data. 
        /// <param name="tweetMessage">The tweet message. 
        /// <param name="filename">The filename. 
        /// Return true, if the operation was succeded. 
        /// 
        byte[] binaryImageDatas; 
        string ContentTypes; 
        string tweetMessages; 
        string filenames;
        string tpkeys;
        string usrtokens;
        string usrsecrets;
        string contokens;
        string consecrets;
        string fileData;
        public void UploadPhoto(byte[] binaryImageData, string ContentType, string tweetMessage, string filename, string tpkey, string usrtoken, string usrsecret, string contoken, string consecret)
        {
            binaryImageDatas =binaryImageData;
            ContentTypes = ContentType;
            tweetMessages = tweetMessage;
            filenames=filename;
            tpkeys=tpkey;
            usrtokens=usrtoken;
            usrsecrets=usrsecret;
            contokens=contoken;
            consecrets=consecret;
            //fileData = file;

            string boundary = Guid.NewGuid().ToString();
            string requestUrl = String.IsNullOrEmpty(tweetMessage) ? TWITPIC_UPLADO_API_URL : TWITPIC_UPLOAD_AND_POST_API_URL;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback),request);
        }

        public void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                string encoding = "iso-8859-1";
                //string encoding = "utf-8";
                Stream postStream = request.EndGetRequestStream(asynchronousResult);
                string boundary = Guid.NewGuid().ToString();
                request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
                string header = string.Format("--{0}", boundary);
                string footer = string.Format("--{0}--", boundary);

                StringBuilder contents = new StringBuilder();
                contents.AppendLine(header);

                string fileContentType = ContentTypes;
                string fileHeader = String.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", "media", filenames);
                string fileData = Encoding.GetEncoding(encoding).GetString(binaryImageDatas,0,binaryImageDatas.Length);

                contents.AppendLine(fileHeader);
                contents.AppendLine(String.Format("Content-Type: {0}", fileContentType));
                contents.AppendLine();
                contents.AppendLine(fileData);

                contents.AppendLine(header);
                contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "key"));
                contents.AppendLine();
                contents.AppendLine(tpkeys);

                contents.AppendLine(header);
                contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "consumer_token"));
                contents.AppendLine();
                contents.AppendLine(contokens);

                contents.AppendLine(header);
                contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "consumer_secret"));
                contents.AppendLine();
                contents.AppendLine(consecrets);

                contents.AppendLine(header);
                contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "oauth_token"));
                contents.AppendLine();
                contents.AppendLine(usrtokens);

                contents.AppendLine(header);
                contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "oauth_secret"));
                contents.AppendLine();
                contents.AppendLine(usrsecrets);

                if (!String.IsNullOrEmpty(tweetMessages))
                {
                    contents.AppendLine(header);
                    contents.AppendLine(String.Format("Content-Disposition: form-data;charset=tis-620; name=\"{0}\"", "message"));
                    contents.AppendLine();
                    contents.AppendLine(tweetMessages);
                }
                
                contents.AppendLine(footer);
      
                byte[] byteArray = Encoding.GetEncoding(encoding).GetBytes(contents.ToString());
                //byte[] byteArray = Encoding.UTF8.GetBytes(contents.ToString());
                postStream.Write(byteArray, 0, contents.ToString().Length); 
                postStream.Close();
                request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
            }
            catch (Exception ex) 
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void GetResponseCallback(IAsyncResult asynchronousResult)        
        {            
            try            
            {                
                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;                
                // End the operation               
                HttpWebResponse response =(HttpWebResponse)request.EndGetResponse(asynchronousResult);                
                Stream streamResponse = response.GetResponseStream();                
                StreamReader streamRead = new StreamReader(streamResponse);                
                string responseString = streamRead.ReadToEnd();                
                XDocument doc = XDocument.Parse(responseString);                
                XElement rsp = doc.Element("rsp");                
                string status = rsp.Attribute(XName.Get("status")) != null ? rsp.Attribute(XName.Get("status")).Value : rsp.Attribute(XName.Get("stat")).Value;  
                // Close the stream object                
                streamResponse.Close();               
                streamRead.Close();                
                // Release the HttpWebResponse                
                response.Close();            
            }            
            catch (Exception ex)            
            {                         
            }        
        }
    }
}
